package com.tarena.elts.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.tarena.elts.entity.EntityContext;
import com.tarena.elts.entity.ExamInfo;
import com.tarena.elts.entity.Question;
import com.tarena.elts.entity.QuestionInfo;
import com.tarena.elts.entity.User;

public class ExamServiceImp implements ExamService{
	private int score =0;
	private boolean finished;
	private User loginUser;
	private List<QuestionInfo> paper = new ArrayList<QuestionInfo>();
	private EntityContext entityContext;
	public void setEntityContext(EntityContext entityContext) {
		this.entityContext = entityContext;
	}
	@Override
	public User login(int id, String pwd) throws IdOrPwdException {
		// TODO Auto-generated method stub
		User user = entityContext.findUserbyId(id);
		if(user==null){
			throw new IdOrPwdException("用户不存在");
		}
		if(user.getPasswd().equals(pwd)){
			this.loginUser=user;
			return user;
		}
		throw new IdOrPwdException("密码错误");
	}
	/**
	 * 开始考试
	 *  1) 抽取考题组织考卷
	 *  2）创建考试信息对象
	 *  3）返回考试信息
	 */
	@Override
	public ExamInfo start() {
		// TODO Auto-generated method stub
		if(finished){
			throw new RuntimeException("考试已结束");
		}
		createPaper();
		ExamInfo info = new ExamInfo();
		info.setQuestionCount(paper.size());
		info.setTimeLimit(entityContext.getTimeLimit());
		info.setTitle(entityContext.getTitle());
		info.setUser(loginUser);
		return info;
	}
	@Override
	public QuestionInfo getQuestion(int index) {
		// TODO Auto-generated method stub
		return paper.get(index);
	}
	/**
	 * 生成考卷，每个级别抽取两道试题
	 */
	private void createPaper(){
		paper.clear();
		Random random = new Random();
		int i=0;
		for (int level = Question.LEVEL1; level <= Question.LEVEL10; level++) {
			List<Question> list = entityContext.findQuestions(level);
			Question question = list.remove(random.nextInt(list.size()));
			Question question2 = list.remove(random.nextInt(list.size()));
			paper.add(new QuestionInfo(i++,question));
			paper.add(new QuestionInfo(i++,question2));
		}
	}
	@Override
	public void saveUserAnswers(int index,List<Integer> list) {
		// TODO Auto-generated method stub
		QuestionInfo questionInfo = paper.get(index);
		questionInfo.setUserAnswers(new ArrayList<Integer>(list));
	}
	@Override
	public int over() {
		// TODO Auto-generated method stub
		if(finished){
			throw new RuntimeException("考试已结束");
		}
		for(QuestionInfo q : paper){
			Question question = q.getQuestion();
			if(question.getAnswers().equals(q.getUserAnswers())){
				score+=question.getScore();
			}
		}
		finished=true;
		return score;
	}
	@Override
	public int getScore() {
		// TODO Auto-generated method stub
		if(!finished){
			throw new RuntimeException("考试还未开始，没有分数");
		}
		return score;
	}
}
